// 非vue组件需要引入
import {getRequest} from "./api";

export const initMenu = (router,store) => {
    // 如果已经初始化过了,就没必要了
    if(store.state.routes.length>0){
        return;
    }
    // 尚未初始化
    getRequest('/system/config/menu').then(data => {
        // 拿到数据判断存不存在
        console.log(data);
        if(data){
            // 格式化Router
            let fmtRoutes = formatRoutes(data);
            // 添加到路由Router
            router.addRoutes(fmtRoutes);
            // 数据存入vuex
            store.commit('initRoutes',fmtRoutes);
        }
    })
}

export const formatRoutes = (routes) => {
    let fmtRoutes = [];
    routes.forEach(router => {
        let{
            path,
            component,
            name,
            iconCls,
            children,
            hidden,
        } = router;
        if(children && children instanceof Array){
            // 递归
            children = formatRoutes(children);
        }
        let fmtRouter = {
            path: path,
            name: name,
            iconCls: iconCls,
            children: children,
            hidden: hidden,
            component(resolve){
                // 软加载,根据命名的特殊性获取组件
                if(component.startsWith('Home')){
                    require(['../views/'+component+'.vue'],resolve);
                }else if(component.startsWith('Student')){
                    require(['../views/student/'+component+'.vue'],resolve);
                }else if(component.startsWith('Admin')){
                    require(['../views/admin/'+component+'.vue'],resolve);
                }else if(component.startsWith('Teacher')){
                    require(['../views/teacher/'+component+'.vue'],resolve);
                }else if(component.startsWith('Common')){
                    require(['../views/common/'+component+'.vue'],resolve);
                }
            }
        }
        fmtRoutes.push(fmtRouter);
    });
    return fmtRoutes;
}
